import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

// 进度条配置
NProgress.configure({
  showSpinner: false
})

// 白名单
const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  // 页面标题
  document.title = getPageTitle(to.meta.title)

  //
  const hasToken = getToken()

  if (hasToken) {
    // 加载全局数据字典
    if (!store.getters.dictionaryConfig || store.getters.dictionaryConfig.length === 0) {
      store.dispatch('dictionaryConfig/addConfig')
    }
    // 加载附件配置
    if (Object.keys(store.getters.fileUploadConfig).length === 0) store.dispatch('fileUploadConfig/addConfig')
    // 加载站点信息配置
    if (Object.keys(store.getters.siteConfig).length === 0) store.dispatch('siteConfig/addSiteConfig')

    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 管理员权限判断
      const hasUserPermissions = store.getters.userPermissions && store.getters.userPermissions.length > 0
      if (hasUserPermissions) {
        next()
      } else {
        try {
          // 获取个人资料、生成权限
          await store.dispatch('user/getProfile')

          // 添加菜单
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
